package com.lw.leetcode.bit.a;

/**
 * Created with IntelliJ IDEA.
 * 693. 交替位二进制数
 *
 * @author liw
 * @version 1.0
 * @date 2021/8/26 14:21
 */
public class HasAlternatingBits {

    public static void main(String[] args) {
        HasAlternatingBits test = new HasAlternatingBits();

        for (int i = 1; i < 10000; i++) {
            boolean a = test.hasAlternatingBits(i);
            boolean b = test.hasAlternatingBits2(i);
            if (a != b) {
                System.out.println(i);
            }
        }
        boolean b = test.hasAlternatingBits(9);
        System.out.println("OK");
    }

    public boolean hasAlternatingBits(int n) {
        int item = n & 3;
        if (item == 3 || item == 0) {
            return false;
        }
        n >>= 2;
        while (n > 0) {
            if ((n & 3) != item) {
                return false;
            }
            n >>= 2;
        }
        return true;
    }


    public boolean hasAlternatingBits2(int n) {
        int xor = (n ^ (n >> 1)) + 1;
        return (xor & (xor - 1)) == 0;
    }


}
